package com.audaque.springboot.foshanupload.web.handler;


import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.core.properties.SwitchProperties;
import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.web.exception.RException;
import com.audaque.springboot.foshanupload.web.util.ExceptionHandlerUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cyb
 * @ExceptionHandle注解——只能在控制器中定义异常处理方法。
 * @since 2020/12/31
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private SwitchProperties switchProperties;


    @ExceptionHandler(value = DuplicateKeyException.class)
    public Object defaultErrorHandler(DuplicateKeyException e, HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return ExceptionHandlerUtils.commonErrorHandler(e, ResultCodeEnum.DUPLICATE_KEY, null, null, switchProperties);
    }


    @ExceptionHandler(value = Error.class)
    public Object defaultErrorHandler(Error e, HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return ExceptionHandlerUtils.commonErrorHandler(e, null, null, null, switchProperties);
    }


    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(Exception e, HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return ExceptionHandlerUtils.commonErrorHandler(e, null, null, null, switchProperties);
    }

    //捕获运行时异常


    @ExceptionHandler(value = RuntimeException.class)
    public Object defaultErrorHandler(RuntimeException e, HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return ExceptionHandlerUtils.commonErrorHandler(e, null, null, null, switchProperties);
    }


    @ExceptionHandler(value = RException.class)
    public Object defaultErrorHandler(RException e, HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return ExceptionHandlerUtils.commonErrorHandler(e, null, null, null, switchProperties);
    }



}

